<?php

namespace App\Http\Controllers\Images;

use App\Http\Requests\Images\ImagesRequests;
use App\Models\Img;
use App\Models\Image;
use App\Models\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;

class ImagesController extends Controller
{
    /** 列表 */
    public function index(Request $request)
    {
        $model = Image::paginate(11);
        return view('images.index', compact('model'));
    }

    /** 添加 */
    public function edit(Request $request)
    {
        $id = $request->get('id');

        if($id){
            $model = Image::with('img')->where('id',$id)->first();
        }else{
            $model = new Image();
        }

        return view('images.edit',compact('model'));
    }

    public function save(ImagesRequests $request){
        $data = $request->input();

        $user_id = empty($data['user_id'])?(User::randId()):$data['user_id'];

        $model = new Image();
        $model->title       = $data['title'];
        $model->description = $data['description'];
        $model->cover       = $data['cover'];
        $model->tabs        = $data['tabs'];
        $model->user_id     = $user_id;
        $model->save();
        $img = array();
        foreach ($data['imgs'] as $k=>$item){
            $img[] = ['image_id'=>$model->id,'sort'=>$k,'url'=>$item,'created_at'=>time(),'updated_at'=>time()];
        }
        Img::insert($img);

        return $this->success('提交成功!,请耐心等待站长审核...');
    }

    /** 预览 */
    public function detail(Request $request)
    {
        $id    = $request->get('id', 1);
        $model = Image::find($id);

        return view('images.detail', compact('model'));
    }
}
